#include "removestuface.h"
#include "ui_removestuface.h"

removeStuface::removeStuface(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::removeStuface)
{
    ui->setupUi(this);

    appDir = QCoreApplication::applicationDirPath();
}

void removeStuface::on_sureBtn_clicked()
{
    QFile stufile(appDir + "/stuInfo.txt");
    if (stufile.exists() == false)
    {
        qDebug() << "创建stuInfo文件" << endl;
    }

    stufile.open(QIODevice::ReadOnly);

    QStringList lines;  //字符串链表

    while (stufile.atEnd() == false) //文件没结束
    {
        QString line = stufile.readLine(); // 读取每一行字符串
        lines.append(line);    //读取每一行字符串到链表中
    }
    stufile.close();

    // 查找并删除目标行
    bool found = false;
    for (int idx = 0; idx < lines.size(); ++idx)
    {
        QString data = lines[idx];
        if (lines[idx].split("+")[0] == ui->le_stuname->text())
        {
            if (lines[idx].split("+")[3].split("\n")[0].toInt() <= 0)
            {
                lines.removeAt(idx);    // 删除该行
                found = true;
                break; // 只需要删除第一个匹配项
            }
            else
            {
                QMessageBox::warning(this, "删除失败", "该学生有未归还的图书");
                return;
            }
        }
    }

    if (!found) //没找到
    {
        QMessageBox::warning(this, "删除失败", "该学生不存在");
        return;
    }
    else
    {
        QMessageBox::warning(this, "删除成功", "该学生已删除");
        ui->le_stuname->clear();
        this->hide();
    }

    stufile.open(QIODevice::WriteOnly);

    QTextStream out(&stufile);
    // 设置编码为 UTF-8
    out.setCodec("UTF-8");
    for (int idx = 0; idx < lines.size(); idx++)
    {
        out << lines[idx];
    }

    stufile.close();

    emit updataView();
}

void removeStuface::on_cancelBtn_clicked()
{
    this->hide();
    ui->le_stuname->clear();
}

removeStuface::~removeStuface()
{
    delete ui;
}
